package me.numark;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.picasso.Picasso;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.numark.model.Comment;
import me.numark.model.CommentsResponse;
import me.numark.model.Feed;
import me.numark.net.BaseResponse;
import me.numark.net.GsonRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.utils.Constants;
import me.numark.utils.Settings;
import me.numark.utils.Utils;
import me.numark.view.CircleImageView;
import me.numark.view.FeedViewHolder;


public class CommentActivity extends BaseActivity
        implements View.OnClickListener, PullToRefreshListView.OnRefreshListener2,
        AdapterView.OnItemClickListener {

    @InjectView(R.id.back)
    View back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_text)
    View rightView;

    @InjectView(R.id.comment_list)
    PullToRefreshListView listView;

    @InjectView(R.id.comment_edit)
    EditText commentEdit;

    @InjectView(R.id.publish_button)
    TextView publishButton;

    private Feed mFeed;

    private CommentAdapter mAdapter;

    private String mReply;

    private String mReplyId;

    private FeedViewHolder mHeaderView;

    private Date yesterday, today, year;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        ButterKnife.inject(this);
        mFeed = Feed.fromString(getIntent().getStringExtra(Constants.FEED_EXTRA));
        back.setOnClickListener(this);
        title.setText(R.string.comment);
        rightView.setVisibility(View.INVISIBLE);
        publishButton.setOnClickListener(this);
        mAdapter = new CommentAdapter();
        listView.setAdapter(mAdapter);
        listView.setOnRefreshListener(this);
        View headerView = getLayoutInflater().inflate(R.layout.feed_list_item, null);
        headerView.setPadding(0, 0, 0, 0);
        mHeaderView = new FeedViewHolder(headerView, this);
        bindHeader();
        listView.getRefreshableView().addHeaderView(headerView);
        listView.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
        listView.setOnItemClickListener(this);
    }

    private void bindHeader() {
        initDate();
        mHeaderView.bindFeedView(mFeed, yesterday, today, year, true);
    }

    private void initDate() {
        Date[] dates = Utils.getMarkDate();
        yesterday = dates[0];
        today = dates[1];
        year = dates[2];
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.publish_button:
                if (!TextUtils.isEmpty(commentEdit.getText().toString())) {
                    publicComment(mReply, mReplyId);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        getComments(0);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        getComments(mAdapter.getCount());
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position < 2) {
            return;
        }
        final int pos = position - 2;
        Comment comment = mAdapter.getItem(pos);
        commentEdit.setHint("@" + comment.user.nick + " ");
        mReply = Integer.toString(comment.user.uid);
        mReplyId = Integer.toString(comment.id);
    }

    private class CommentAdapter extends BaseAdapter {

        Date today, yesterday, year;

        public CommentAdapter() {
            super();
            Date[] dates = Utils.getMarkDate();
            today = dates[0];
            yesterday = dates[1];
            year = dates[2];
        }

        @Override
        public int getCount() {
            return mComments.size();
        }

        @Override
        public Comment getItem(int position) {
            return mComments.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            ViewHolder holder;
            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.feed_comment_list_item, parent, false);
                holder = new ViewHolder(view);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            Comment comment = getItem(position);
            Picasso.with(CommentActivity.this).load(comment.user.pic).into(holder.avatar);
            holder.name.setText(comment.user.nick);
            holder.userComment.setText(comment.description);
            holder.commentTime
                    .setText(Utils.getTimeShowText(comment.getDate(), yesterday, today, year));
            return view;
        }
    }

    public class ViewHolder {

        @InjectView(R.id.avatar)
        CircleImageView avatar;

        @InjectView(R.id.name)
        TextView name;

        @InjectView(R.id.user_comment)
        TextView userComment;

        @InjectView(R.id.comment_time)
        TextView commentTime;

        public ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }

    private List<Comment> mComments = new ArrayList<Comment>();

    private void getComments(final int start) {
        String url = String.format(NetworkConstants.FEED_COMMENT_URL, Settings.getUid(), mFeed.id);
        Map<String, String> body = new HashMap<String, String>();
        body.put("start", Integer.toString(start));
        body.put("limit", "20");
        GsonRequest<CommentsResponse> request = new GsonRequest<CommentsResponse>(url,
                Request.Method.GET, CommentsResponse.class, true, body,
                new Response.Listener<CommentsResponse>() {
                    @Override
                    public void onResponse(CommentsResponse response) {
                        listView.onRefreshComplete();
                        if (response.ret && response.data != null) {
                            if (start == 0) {
                                mComments.clear();
                            }
                            mComments.addAll(Arrays.asList(response.data));
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listView.onRefreshComplete();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }

    private void publicComment(String reply, String replyId) {
        String url = String.format(NetworkConstants.SHARE_COMMENTS_URL, Settings.getUid());
        Map<String, String> body = new HashMap<String, String>();
        if (reply != null) {
            body.put("reply", reply);
        }
        if (replyId != null) {
            body.put("reply_id", replyId);
        }
        body.put("nsid", Integer.toString(mFeed.id));
        body.put("description", commentEdit.getText().toString());
        GsonRequest<FeedResponse> request = new GsonRequest<FeedResponse>(url, Request.Method.POST,
                FeedResponse.class, true, body, new Response.Listener<FeedResponse>() {
            @Override
            public void onResponse(FeedResponse response) {
                dismissProgress();
                if (response.ret) {
                    Toast.makeText(CommentActivity.this, R.string.comment_success,
                            Toast.LENGTH_SHORT).show();
                    commentEdit.setText("");
                    mFeed = response.data;
                    bindHeader();
                    getComments(0);
                } else {
                    Toast.makeText(CommentActivity.this, response.msg, Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissProgress();
                Toast.makeText(CommentActivity.this, R.string.generic_network_error,
                        Toast.LENGTH_SHORT).show();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
        showProgress();
    }

    public static class FeedResponse extends BaseResponse {

        public Feed data;
    }
}
